<template>
  <div class="form-container" v-loading="loading">
    <div class="left-board">
      <el-scrollbar class="left-scrollbar">
        <div class="components-list">
          <div v-for="(item, listIndex) in leftComponents" :key="listIndex">
            <div class="components-title">
              {{ item.title }}
            </div>
            <draggable
              v-if="formshow > 0"
              class="components-draggable"
              :list="item.list"
              :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
              :clone="cloneComponent"
              draggable=".components-item"
              :sort="false"
              @end="onEnd"
            >
              <div
                v-for="(element, index) in item.list"
                :key="index"
                class="components-item"
                @click="addComponent(element)"
              >
                <div class="components-body">
                  {{ element.__config__.label }}
                </div>
              </div>
            </draggable>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <div class="center-board">
      <div class="action-bar">
        <el-button icon="el-icon-video-play" type="text" @click="saveForm">
          保存
        </el-button>
        <el-button icon="el-icon-view" type="text" @click="preview">
          预览
        </el-button>
        <el-button class="delete-btn" icon="el-icon-delete" type="text" @click="empty">
          清空
        </el-button>
      </div>
      <el-scrollbar class="center-scrollbar">
        <el-row class="center-board-row" :gutter="formConf.gutter">
          <el-form
            :size="formConf.size"
            :label-position="formConf.labelPosition"
            :disabled="formConf.disabled"
            :label-width="formConf.labelWidth + 'px'"
          >
            <draggable class="drawing-board" :list="drawingList" :animation="340" group="componentsGroup">
              <draggable-item
                v-for="(item, index) in drawingList"
                :key="item.renderKey"
                :drawing-list="drawingList"
                :current-item="item"
                :index="index"
                :active-id="activeId"
                :form-conf="formConf"
                @activeItem="activeFormItem"
                @copyItem="drawingItemCopy"
                @deleteItem="drawingItemDelete"
              />
            </draggable>
            <div v-show="!drawingList.length" class="empty-info">
              从左侧拖入或点选组件进行表单设计
            </div>
          </el-form>
        </el-row>
      </el-scrollbar>
    </div>

    <right-panel
      :active-data="activeData"
      :form-conf="formConf"
      :show-field="!!drawingList.length"
      @fetch-data="fetchData"
    />

    <form-drawer
      :visible.sync="drawerVisible"
      :form-data="drawingList"
      size="100%"
      :generate-conf="generateConf"
    />
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { debounce } from 'throttle-debounce'
import render from '@/components/render/render'
import FormDrawer from './FormDrawer'
import RightPanel from './RightPanel'
import {
  inputComponents, selectComponents, layoutComponents, formConf
} from '@/components/generator/config'
import {
  exportDefault, beautifierConf, isNumberStr, titleCase, deepClone, isObjectObject
} from '@/utils/index'
import drawingDefalut from '@/components/generator/drawingDefalut'
import DraggableItem from './DraggableItem'
import {IdToTag, tagToIdType} from './keyFilter'
import {
  getDrawingList, saveDrawingList, getIdGlobal, saveIdGlobal, getFormConf
} from '@/utils/db'
import { selectMetaDataList, selectForm, addApplication, saveOrUpdate } from '@/api/design'

let beautifier
const emptyActiveData = { style: {}, autosize: {} }
let oldActiveId
let tempActiveData
const drawingListInDB = null
const formConfInDB = getFormConf()
const idGlobal = getIdGlobal()

export default {
  components: {
    draggable,
    render,
    FormDrawer,
    RightPanel,
    DraggableItem
  },
  data() {
    return {
      loading: false,
      idGlobal,
      formConf,
      inputComponents,
      selectComponents,
      layoutComponents,
      labelWidth: 100,
      drawingList: drawingDefalut,
      drawingData: {},
      activeId: drawingDefalut[0].formId,
      drawerVisible: false,
      formData: {},
      dialogVisible: false,
      generateConf: null,
      showFileName: false,
      activeData: drawingDefalut[0],
      saveDrawingListDebounce: debounce(340, saveDrawingList),
      saveIdGlobalDebounce: debounce(340, saveIdGlobal),
      formshow: false,
      leftComponents: [
        {
          title: '基础字段',
          list: []
        },
        {
          title: '增强字段',
          list: selectComponents
        },
        {
          title: '部门成员字段',
          list: layoutComponents
        }
      ],
      // 基础属性
      baseAttrMain: {
        // 其余的为可直接写在组件标签上的属性
        placeholder: '请输入',
        style: { width: '100%' },
        clearable: true,
        'prefix-icon': '',
        'suffix-icon': '',
        maxlength: null,
        'show-word-limit': false,
        readonly: false,
        disabled: false
      },
      baseAttrConfig: {
        // 组件的自定义配置
        label: '',
        metaDataTypeCode: '',
        labelWidth: null,
        showLabel: true,
        changeTag: true,
        tag: '',
        tagIcon: '',
        defaultValue: undefined,
        required: true,
        layout: 'colFormItem',
        span: 24,
        document: '',
        // 正则校验规则
        regList: []
      },
      baseAttrSlot: {
        prepend: '',
        append: ''
      }
    }
  },
  computed: {
  },
  watch: {
    '$store.state.design.subformActiveId': {
      // 监听子表单选中组件，更新右侧属性
      handler(val) {
        this.activeData = val
      },
      deep: true
    },
    '$store.state.design.subFormFlag': {
      // 监听子表单,更新主表单中children数据
      handler() {
        this.upDateFormListForSubform()
      }
    },
    activeId: {
      handler(val) {
        oldActiveId = val
      },
      immediate: true
    },
    drawingList: {
      handler(val) {
        this.saveDrawingListDebounce(val)
        if (val.length === 0) this.idGlobal = 100
      },
      deep: true
    },
    idGlobal: {
      handler(val) {
        this.saveIdGlobalDebounce(val)
      },
      immediate: true
    }
  },
  created() {
    this.getMetaDataList()
  },
  mounted() {
    if (Array.isArray(drawingListInDB) && drawingListInDB.length > 0) {
      this.drawingList = drawingListInDB
    } else {
      this.drawingList = drawingDefalut
    }
    this.activeFormItem(this.drawingList[0])
    if (formConfInDB) {
      this.formConf = formConfInDB
    }
  },
  methods: {
    // 子表单数据更新formlist
    upDateFormListForSubform() {
      this.drawingList.forEach((farItem, farIndex) => {
        if(farItem.__config__.tag == 'subform') {
          let sonIndex = this.$store.state.design.subFormInfo.findIndex(every => every.formId == farItem.__config__.formId)
          this.drawingList[farIndex].subFormFieldAttrList = this.getFormItemData(this.$store.state.design.subFormInfo[sonIndex].value)
        }
      })
      console.log(this.drawingList)
    },
    // 获取左侧字段数据
    async getMetaDataList() {
      // localStorage.clear()
      let res = await selectMetaDataList()
      let basics = []
      let heighten = []
      res.data[0].formMetaDataItemVoList.forEach(item => {
        const every = {
          __config__: {
            ...this.baseAttrConfig,
            label: item.metaDataName,
            metaDataTypeCode: item.metaDataTypeCode,
            tag: IdToTag(item.metaDataCode)
          },
          __slot__: {...this.baseAttrSlot},
          ...this.baseAttrMain
        }
        basics.push(every)
      })
      res.data[1].formMetaDataItemVoList.forEach(item => {
        const every = {
          __config__: {
            ...this.baseAttrConfig,
            label: item.metaDataName,
            metaDataTypeCode: item.metaDataTypeCode,
            tag: IdToTag(item.metaDataCode)
          },
           __slot__: {...this.baseAttrSlot},
          ...this.baseAttrMain
        }
        heighten.push(every)
      })
      this.formshow = true
      this.leftComponents[0].list = basics
      this.leftComponents[1].list = heighten
      if(this.$route.params.appId && this.$route.params.busiKey) {
        // 更新历史数据
        this.updateForm()
      }
    },
    // 获取更新表单数据
    async updateForm() {
      this.drawingList = []
      let res = await selectForm(this.$route.params)
      if(res.code == 200) {
        res.data.formFieldAttrList.forEach((item, index) => {
          let temp = {
            __config__: {
              ...this.baseAttrConfig,
              label: item.title,
              metaDataTypeCode: item.metaDataTypeCode,
              tag: IdToTag(item.metaDataCode),
              formId: index,
              renderKey: new Date().getTime() 
            },
            __slot__: {...this.baseAttrSlot},
            ...this.baseAttrMain
          }
          if(item.metaDataCode == 'subform') {
            temp.subFormFieldAttrList = []
            item.subFormFieldAttrList.forEach((sonItem, sonIndex) => {
              let sonTemp = {
                __config__: {
                  ...this.baseAttrConfig,
                  label: sonItem.title,
                  metaDataTypeCode: sonItem.metaDataTypeCode,
                  tag: IdToTag(sonItem.metaDataCode),
                  formId: new Date().getTime() + sonIndex,
                  renderKey: new Date().getTime() 
                },
                __slot__: {...this.baseAttrSlot},
                ...this.baseAttrMain
              }
              temp.subFormFieldAttrList.push(sonTemp)
            })
          }
          console.log(temp)
          this.drawingList.push(temp)
        })
      }
    },
    setObjectValueReduce(obj, strKeys, data) {
      const arr = strKeys.split('.')
      arr.reduce((pre, item, i) => {
        if (arr.length === i + 1) {
          pre[item] = data
        } else if (!isObjectObject(pre[item])) {
          pre[item] = {}
        }
        return pre[item]
      }, obj)
    },
    setRespData(component, resp) {
      const { dataPath, renderKey, dataConsumer } = component.__config__
      if (!dataPath || !dataConsumer) return
      const respData = dataPath.split('.').reduce((pre, item) => pre[item], resp)

      // 将请求回来的数据，赋值到指定属性。
      // 以el-tabel为例，根据Element文档，应该将数据赋值给el-tabel的data属性，所以dataConsumer的值应为'data';
      // 此时赋值代码可写成 component[dataConsumer] = respData；
      // 但为支持更深层级的赋值（如：dataConsumer的值为'options.data'）,使用setObjectValueReduce
      this.setObjectValueReduce(component, dataConsumer, respData)
      const i = this.drawingList.findIndex(item => item.__config__.renderKey === renderKey)
      if (i > -1) this.$set(this.drawingList, i, component)
    },
    fetchData(component) {
      const { dataType, method, url } = component.__config__
      if (dataType === 'dynamic' && method && url) {
        this.setLoading(component, true)
        this.$axios({
          method,
          url
        }).then(resp => {
          this.setLoading(component, false)
          this.setRespData(component, resp.data)
        })
      }
    },
    setLoading(component, val) {
      const { directives } = component
      if (Array.isArray(directives)) {
        const t = directives.find(d => d.name === 'loading')
        if (t) t.value = val
      }
    },
    activeFormItem(currentItem) {
      this.activeData = currentItem
      this.activeId = currentItem.__config__.formId
    },
    onEnd(obj) {
      if (obj.from !== obj.to) {
        this.fetchData(tempActiveData)
        this.activeData = tempActiveData
        this.activeId = this.idGlobal
      }
    },
    addComponent(item) {
      const clone = this.cloneComponent(item)
      this.fetchData(clone)
      this.drawingList.push(clone)
      this.activeFormItem(clone)
    },
    cloneComponent(origin) {
      const clone = deepClone(origin)
      const config = clone.__config__
      config.span = this.formConf.span // 生成代码时，会根据span做精简判断
      this.createIdAndKey(clone)
      clone.placeholder !== undefined && (clone.placeholder += config.label)
      tempActiveData = clone
      return tempActiveData
    },
    createIdAndKey(item) {
      const config = item.__config__
      config.formId = ++this.idGlobal
      config.renderKey = `${config.formId}${+new Date()}` // 改变renderKey后可以实现强制更新组件
      if (config.layout === 'colFormItem') {
        item.__vModel__ = `field${this.idGlobal}`
      } else if (config.layout === 'rowFormItem') {
        config.componentName = `row${this.idGlobal}`
        !Array.isArray(config.children) && (config.children = [])
        delete config.label // rowFormItem无需配置label属性
      }
      if (Array.isArray(config.children)) {
        config.children = config.children.map(childItem => this.createIdAndKey(childItem))
      }
      return item
    },
    generate(data) {
      const func = this[`exec${titleCase(this.operationType)}`]
      this.generateConf = data
      func && func(data)
    },
    preview() {
      this.drawerVisible = true
    },
    saveForm() {
      if(this.$route.params.appId) {
        let param = this.getCurrentData(this.$route.params.appCode)
        this.saveOrUpdate(param)
      }else {
        this.addApplication()
      }
    },
    // 没有通过新增应用入口进入的新增表单请求，先执行新增表单
    async addApplication() {
      let param = {
        appCode: "",
        appName: '未命名应用',
        icon: "",
        id: null
      }
      let res = await addApplication(param)
      if(res.code == 200) {
        let param = this.getCurrentData(res.data.id)
        this.saveOrUpdate(param)
      }
    },
    // 提交表单请求
    async saveOrUpdate(param) {
      this.loading = true
      let res = await saveOrUpdate(param)
      this.loading = false
      console.log(res)
      if(res.code == 200) {
        this.$confirm('保存成功?', '提示', {
          confirmButtonText: '跳转应用表单列表',
          cancelButtonText: '继续编辑当前表单',
          type: 'warning'
        }).then(() => {
          this.$router.push({path: '/application/'+ res.data.appId +'/common/'+ res.data.busiKey})
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '表单保存成功'
          })
        })
      }
    },
    getFormItemData(data) {
      let temp = []
      data.forEach((item, index) => {
        let objTemp = {
          "busiKey":"",
          "constantFormat":null,
          "defaultVal":null,
          "description":null,
          "fieldAuthRule":null,
          "title": item.__config__.label,
          "fieldValidatorRule":null,
          "fieldWidthRule":null,
          "formId":null,
          "hasScanInput":null,
          "hasShowName":null,
          "id":null,
          "metaDataCode": tagToIdType(item.__config__.tag)[0],
          "metaDataTypeCode": tagToIdType(item.__config__.tag)[1],
          "sanInputId":null,
          "showFormat":null,
          "sort": index,
          "tipsMsg":null
        }
        if(item.__config__.tag == 'subform') {
          objTemp.subFormFieldAttrList = item.subFormFieldAttrList
        }
        temp.push(objTemp)
      })
      return temp
    },
    getCurrentData(appCode) {
      return {
        "appId": this.$route.params.appId,
        "busiKey":"",
        "formFieldAttrList":this.getFormItemData(this.drawingList),
        "formLayoutRule":"",
        "title":this.$store.state.design.navName,
        "formStyleTemplate":{
            "content":"",
            "formStyleCustom":{
                "alignment":"",
                "backgroundName":"",
                "backgroundValue":"",
                "fontStyle":"",
                "formHeadStyleName":"",
                "formHeadStyleValue":"",
                "id":null,
                "submitBtnColor":""
            },
            "formStyleCustomId":null,
            "id":null,
            "subjectDes":"",
            "subjectName":"",
            "subjectType":""
        },
        "formStyleTemplateId":null,
        "hasCache":0,
        "hasLabelsShow":0,
        "hasSubmit":0,
        "id":null,
        "labelsValues":"",
        "notShowRule":"",
        "showRuleCondition":{
            "conditionExpressionId":null,
            "conditionName":"",
            "conditionValue":"",
            "effectConditionRule":"",
            "id":null,
            "showFields":""
        },
        "showRuleId":null,
        "submitValidatorCondition":{
            "availableArgs":"",
            "errTipMsg":"",
            "functionArgsVo":{
                "argsDesc":"",
                "argsName":"",
                "argsType":"",
                "id":null
            },
            "id":null,
            "validatorFormula":""
        },
        "submitValidatorId":null,
        "vueEventCondition":{
            "eventDesc":"",
            "eventName":"",
            "executeAction":0,
            "executeActionId":null,
            "formVueEventExecuteAction":{
                "id":null,
                "requestHeader":"",
                "requestType":"",
                "requestUri":"",
                "respFormat":"",
                "respSettingId":null
            },
            "formVueEventExecuteActionReqDto":{
                "id":null,
                "requestHeader":"",
                "requestType":"",
                "requestUri":"",
                "respFormat":"",
                "respSettingId":null
            },
            "id":null,
            "triggerActionFiledName":""
        },
        "vueEventId":null
    }
    },
    empty() {
      this.$confirm('确定要清空所有组件吗？', '提示', { type: 'warning' }).then(
        () => {
          this.drawingList = []
          this.idGlobal = 100
        }
      )
    },
    drawingItemCopy(item, list) {
      let clone = deepClone(item)
      clone = this.createIdAndKey(clone)
      list.push(clone)
      this.activeFormItem(clone)
    },
    drawingItemDelete(index, list) {
      list.splice(index, 1)
      this.$nextTick(() => {
        const len = this.drawingList.length
        if (len) {
          this.activeFormItem(this.drawingList[len - 1])
        }
      })
    },
    run() {
      this.dialogVisible = true
      this.showFileName = false
      this.operationType = 'run'
    },
    copy() {
      this.dialogVisible = true
      this.showFileName = false
      this.operationType = 'copy'
    }
  }
}
</script>

<style lang='scss'>
@import '@/styles/home';
</style>
